package com.ssyc.gsk_teacher_appraisal.fragment;

import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ssyc.common.adapter.VpCommonAdapter;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.manager.MediaPlayerManager;
import com.ssyc.common.view.vp.SuperViewPager;
import com.ssyc.gsk_teacher_appraisal.R;
import com.ssyc.gsk_teacher_appraisal.activity.TkTeacherAppraisalQuestionActivity;
import com.ssyc.gsk_teacher_appraisal.base.BaseLazyFragment;
import com.ssyc.gsk_teacher_appraisal.bean.QuestionDetailsInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * 听力多题单选
 * Created by Administrator on 2018/9/3 0003.
 */

public class AppraisalListenMultipleChooseFragment extends BaseLazyFragment implements ViewPager.OnPageChangeListener, View.OnClickListener {

    //题目类型
    private TextView tvType;

    //顶部布局
    private LinearLayout llTop;

    //底部布局
    private RelativeLayout rlBottom;

    //标题
    private TextView tvContent;

    //播放按钮
    private ImageView ivPlay;

    //Vp
    private SuperViewPager vp;

    //Vp的指示器
    private TextView tvNum;


    //播放段落音频文件的帧动画对象
    private AnimationDrawable animationDrawable;


    //填充ViewPager的Framgent集合
    private List<Fragment> mFragments;
    //vp的适配器
    private VpCommonAdapter adapter;

    //选项,最多6个
    private String[] letters = {"A", "B", "C", "D", "E", "F"};

    //服务器返回的页面数据对象
    private QuestionDetailsInfo info;

    //播放音频的Url地址,对于单体单选题直接从服务器返回的Url中取
    private String audioUrl = "";

    /**
     * 获取当前Fragment对象方法
     *
     * @return
     */
    public static final AppraisalListenMultipleChooseFragment newInstance(QuestionDetailsInfo info) {
        AppraisalListenMultipleChooseFragment appraisalListenMultipleChooseFragment = new AppraisalListenMultipleChooseFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", info);
        appraisalListenMultipleChooseFragment.setArguments(bundle);
        return appraisalListenMultipleChooseFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_teacher_class_listen_multiple_choose;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

        //初始化视图
        initView(view);

        //获取页面数据
        initIntent();

        //初始化页面数据
        initData();
    }


    /**
     * 获取页面数据
     */
    private void initIntent() {

        //获取服务器返回的页面对象
        info = (QuestionDetailsInfo) getArguments().getSerializable("data");

        if (null == info) {
            return;
        }

        //设置题目类型
        tvType.setText(info.getTitle_type());

        //获取顶部播放的音频Url
        //获取播放音频地址 这里需要拼接前缀
        audioUrl = info.getPath() + info.getContent();
        Log.i("test", "音频是:" + audioUrl);

    }

    /**
     * 创建填充Vp的Fragment集合
     */
    private void initData() {
        mFragments = new ArrayList<>();

        if (info != null) {

            //获取所有小题的解析(听力单题多选对应的是所有小题对应一个解析)
            String analysis = info.getAnalysis();

            //获取所有小题的数据集合
            List<QuestionDetailsInfo.SubListBean> sub_list = info.getSub_list();
            if (null != sub_list && sub_list.size() != 0) {
                for (int i = 0; i < sub_list.size(); i++) {

                    //传递小题的数据模型,小题在答题中的位置,小题的解析数据
                    mFragments.add(AppraisalCommonChooseAnswerFragment.newInstance(sub_list.get(i), i, analysis));
                }
            }

        }

        //设置底部的VP的指示器数字
        tvNum.setText("1/" + mFragments.size());

        //设置ViewPager的数据
        adapter = new VpCommonAdapter(getChildFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(mFragments.size());
    }


    /**
     * 初始化视图
     *
     * @param view
     */
    public void initView(View view) {
        tvType = view.findViewById(R.id.tv_type);
        tvContent = view.findViewById(R.id.tv_content);
        llTop = view.findViewById(R.id.ll_top);
        rlBottom = view.findViewById(R.id.rl_bottom);
        ivPlay = view.findViewById(R.id.iv_play);
        ivPlay.setOnClickListener(this);
        vp = view.findViewById(R.id.vp);
        vp.addOnPageChangeListener(this);
        tvNum = view.findViewById(R.id.tv_num);
        llTop.setVisibility(View.VISIBLE);
        rlBottom.setVisibility(View.VISIBLE);
    }

    /**
     * Vp的选中事件
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        tvNum.setText((position + 1) + "/" + mFragments.size());
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_play) {
            doPlayVoiceAnim(audioUrl);
        }
    }


    /**
     * 音频播放,帧动画播放的方法
     */
    private void doPlayVoiceAnim(String voiceUrl) {
        if (!TextUtils.isEmpty(voiceUrl)) {

            if (null != animationDrawable && animationDrawable.isRunning()) {
                stopVoiceAnim();
            }

            //进行帧动画操作
            animationDrawable = (AnimationDrawable) ivPlay.getBackground();
            if (null == animationDrawable) {
                return;
            }
            animationDrawable.start();
            //播放音频
            MediaPlayerManager.getInstance().play(voiceUrl, new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    if (null != animationDrawable) {
                        stopVoiceAnim();
                    }

                }
            }, new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    if (null != animationDrawable) {
                        stopVoiceAnim();
                    }
                    return false;
                }
            });

        }
    }


    /**
     * 停止帧动画播放,还原按钮状态的方法
     */
    private void stopVoiceAnim() {
        animationDrawable.stop();
        animationDrawable = null;
        ivPlay.setBackgroundResource(R.drawable.teacher_class_voice_big_anim);
        MediaPlayerManager.getInstance().stop();
    }


    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && TkTeacherAppraisalQuestionActivity.VPSCOLL.equals(busInfo.vpScoll)) {
            //Vp的滚动监听事件,如果是正在播放音频状态,停止播放,同时还原按钮状态
            if (null != animationDrawable && animationDrawable.isRunning()) {
                stopVoiceAnim();
            }
        }
    }

    @Override
    public void onDestroy() {
        //停止帧动画
        if (null != animationDrawable && animationDrawable.isRunning()) {
            stopVoiceAnim();
        }
        MediaPlayerManager.getInstance().stop();
        super.onDestroy();
    }
}

